package com.lyl.xxx.modules.framework.security.utils;

import com.lyl.common.exception.BizException;
import com.lyl.common.result.BaseCode;
import com.lyl.xxx.modules.framework.security.model.details.LoginDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author Mr.Luo
 * @date 2022-09-21 16:41
 * @desc security工具类
 */
@Slf4j
public class SecurityUtil {
    private SecurityUtil() {
    }

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static LoginDetails getLoginDetails() {
        try {
            return ((LoginDetails) getAuthentication().getPrincipal());
        } catch (Exception e) {
            throw new BizException(BaseCode.UNAUTHORIZED, "获取登录用户信息异常");
        }
    }

    public static long getUserId() {
        try {
            return getLoginDetails().getSysUser().getUserId();
        } catch (Exception e) {
            throw new BizException(BaseCode.UNAUTHORIZED, "获取登录用户Id异常");
        }
    }

    public static Long getSafeUserId() {
        try {
            return getLoginDetails().getSysUser().getUserId();
        } catch (Exception e) {
            return null;
        }
    }

    public static String getTokenKey() {
        try {
            return getLoginDetails().getToken();
        } catch (Exception e) {
            throw new BizException(BaseCode.UNAUTHORIZED, "获取登录用户token异常");
        }
    }

}
